package com.cobo.common.core;

import org.reflections.Reflections;

import java.io.File;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Set;

public class AnnotationScanner {

    private static final String PACKAGE_NAME = "com"; // 替换为你的包名

    public static void initialPlugin() throws Exception {

        Reflections reflections = new Reflections(PACKAGE_NAME);
        Set<Class<?>> classes = reflections.getTypesAnnotatedWith(Plugin.class);

        for (Class<?> clazz : classes) {
            // 创建类的实例并调用方法（示例）
            Object instance = clazz.getDeclaredConstructor().newInstance();
            // 这里可以添加更多的逻辑来处理实例，比如存储在一个容器中
            System.out.println("Initialized plugin: " + clazz.getCanonicalName());
            Method imethod = clazz.getMethod("install");
            imethod.invoke(instance);
        }
    }

    public static List<Class<?>> getAnnotatedClasses(String packageName, Class<? extends Annotation> annotation) throws Exception {
        List<Class<?>> classes = new ArrayList<>();
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        assert classLoader != null;

        String path = packageName.replace('.', '/');
        Enumeration<URL> resources = classLoader.getResources(path);
        List<File> dirs = new ArrayList<>();

        while (resources.hasMoreElements()) {
            URL resource = resources.nextElement();
            dirs.add(new File(resource.getFile()));
        }

        for (File directory : dirs) {
            classes.addAll(findClasses(directory, packageName, annotation));
        }

        return classes;
    }

    private static List<Class<?>> findClasses(File directory, String packageName, Class<? extends Annotation> annotation) throws Exception {
        List<Class<?>> classes = new ArrayList<>();
        if (!directory.exists()) {
            return classes;
        }

        File[] files = directory.listFiles();
        if (files == null) {
            return classes;
        }

        for (File file : files) {
            if (file.isDirectory()) {
                assert !file.getName().contains(".");
                classes.addAll(findClasses(file, packageName + "." + file.getName(), annotation));
            } else if (file.getName().endsWith(".class")) {
                String className = packageName + '.' + file.getName().substring(0, file.getName().length() - 6);
                Class<?> clazz = Class.forName(className);
                if (clazz.isAnnotationPresent(annotation)) {
                    classes.add(clazz);
                }
            }
        }
        return classes;
    }
}